package com.mezz.bones.im.gateway.handler;

import com.mezz.bones.im.common.domain.user.ImUserConnectInfo;
import com.mezz.bones.im.gateway.manager.UserConnectInfoManager;
import com.mezz.bones.im.gateway.service.IUserChannelService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: zhuang
 * @Date: 2024/12/5 15:35
 * @Description: TODO
 * @Version: 1.0
 **/

@Slf4j
@Component
@ChannelHandler.Sharable
public class ConnectionLifecycleHandler  extends ChannelInboundHandlerAdapter {

    @Resource
    private IUserChannelService userChannelService;

    @Resource
    private UserConnectInfoManager userConnectInfoManager;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("ConnectionLifecycleHandler connect add :{}",ctx.channel().id().asLongText());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        log.info("ConnectionLifecycleHandler connect close :{}",ctx.channel().id().asLongText());

        //连接关闭事件  这边统一处理  ChannelUtil.sendAndGracefullyClose 或者 ctx.close
        //     * 连接下线
        //     * 1. 用户连接主动断开
        //     * 2. 用户设置主动退出 logout
        //     * 3. 用户连接心跳超时
        ImUserConnectInfo userInfo = userConnectInfoManager.getUserConnectInfo(ctx);
        userChannelService.forceOffLine(userInfo);

        if(userInfo == null){
            //未认证的连接 也要从 map中移除
            userChannelService.removeUnAuthChannel(ctx);
        }

        super.channelInactive(ctx);
    }
}